package com.wangmeng.book.client.frame;

import com.wangmeng.book.client.service.CommandService;
import com.wangmeng.book.utils.ConstValueUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * User: 王猛
 * Date: 13-9-26
 */
public class BookRecordManage {
    public static final int PAGE_SIZE = 50;
    private JPanel root;
    private JButton nextPageBnt;
    private JButton forwordPageBnt;
    private JPanel bntPanel;
    private JButton receiveBnt;
    private JButton notReceiveBnt;
    private JTable dataTable;
    private JPanel pagePanel;
    private JScrollPane doc;
    private JTextField titleInput;
    private JComboBox sourceTypeCombo;
    private JButton applyBnt;
    private static Vector headerNames = new Vector();
    private MyCheckAllRenderer allCheck = new MyCheckAllRenderer();
    private int currentPage = 1;
    private Vector data = new Vector();
    private List<Integer> statusList = new ArrayList<Integer>();
    private static JComboBox box = new JComboBox();
    private Map<String, Object> exParam = new HashMap<String, Object>();

    static {
        headerNames.add("");
        headerNames.add("所属分类");
        headerNames.add("ID");
        headerNames.add("标题");
        headerNames.add("作者");
        headerNames.add("原始分类");
        headerNames.add("字数");
        headerNames.add("点击数");
        headerNames.add("原始链接");

        JSONArray partList = CommandService.getInstance().listBookPartition();
        if (partList != null) {
            PartitionComboxItem pi = new PartitionComboxItem();
            pi.setCode("");
            pi.setName("");
            box.addItem(pi);
            for (int i = 0; i < partList.size(); i++) {
                JSONObject item = partList.getJSONObject(i);
                String code = item.getString("code");
                String name = item.getString("name");
                pi = new PartitionComboxItem();
                pi.setCode(code);
                pi.setName((code.length() > 4 ? "--" : "") + name);
                box.addItem(pi);
            }
        }
    }

    class SourceTypeItem implements Serializable {
        private int type;
        private String name;

        public SourceTypeItem(int type, String name) {
            this.type = type;
            this.name = name;
        }

        int getType() {
            return type;
        }

        void setType(int type) {
            this.type = type;
        }

        String getName() {
            return name;
        }

        void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }

    public BookRecordManage() {
        sourceTypeCombo.addItem(new SourceTypeItem(0, "-请选择-"));
        sourceTypeCombo.addItem(new SourceTypeItem(ConstValueUtils.SOURCE_TYPE_TX, "TX"));
        sourceTypeCombo.addItem(new SourceTypeItem(ConstValueUtils.SOURCE_TYPE_WY, "WY"));
        sourceTypeCombo.addItem(new SourceTypeItem(ConstValueUtils.SOURCE_TYPE_SN, "SN"));
        sourceTypeCombo.addItem(new SourceTypeItem(ConstValueUtils.SOURCE_TYPE_SH, "SH"));
        statusList.add(ConstValueUtils.APPROVE_INIT);
        JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "view_count desc",exParam);
        if (dataList != null) {
            if (dataList.size() < PAGE_SIZE) {
                nextPageBnt.setEnabled(false);
            }
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject obj = dataList.getJSONObject(i);
                Vector item = new Vector();
                item.add(false);
                item.add("");
                item.add(obj.getInt("oid"));
                item.add(obj.getString("name"));
                item.add(obj.getString("author"));
                item.add(obj.getString("cate_name"));
                item.add(obj.getInt("word_num"));
                item.add(obj.getString("view_count"));
                String href = obj.getString("href");
                item.add(href);
                data.add(item);
            }
        } else {
            nextPageBnt.setEnabled(false);
        }
        DefaultTableModel tm = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                //禁用可编辑
                if (column > 1) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };
        tm.setDataVector(data, headerNames);
        dataTable.setModel(tm);
        TableColumn tc = dataTable.getColumnModel().getColumn(2);
        tc.setPreferredWidth(0);
        tc.setMaxWidth(0);
        tc.setMinWidth(0);
        tc.sizeWidthToFit();
        dataTable.getTableHeader().getColumnModel().getColumn(2).setMaxWidth(0);
        dataTable.getTableHeader().getColumnModel().getColumn(2).setMinWidth(0);
        tc = dataTable.getColumnModel().getColumn(1);
        tc.setCellEditor(new DefaultCellEditor(box));
        tc.setMinWidth(60);
        tc.setMaxWidth(150);
        tc.setPreferredWidth(100);
        tc = dataTable.getColumnModel().getColumn(0);
        tc.setPreferredWidth(30);
        tc.setMaxWidth(30);
        tc.setMinWidth(30);
        tc.sizeWidthToFit();
        tc.setHeaderRenderer(allCheck);
        tc.setCellEditor(dataTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(dataTable.getDefaultRenderer(Boolean.class));
        tc.getCellEditor().addCellEditorListener(new CellEditorListener() {
            public void editingStopped(ChangeEvent e) {
                int rowNum = dataTable.getRowCount();
                int notNum = 0;
                for (int i = 0; i < rowNum; i++) {
                    Object value = dataTable.getValueAt(i, 0);
                    if (!((Boolean) value)) {
                        notNum++;
                    }
                }
                if (notNum == 0) {
                    allCheck.setSelected(true);
                    dataTable.getTableHeader().repaint();
                } else if (notNum == 1) {
                    allCheck.setSelected(false);
                    dataTable.getTableHeader().repaint();
                }
            }

            public void editingCanceled(ChangeEvent e) {

            }
        });
//        tc = dataTable.getColumnModel().getColumn(7);
        dataTable.getTableHeader().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (dataTable.getColumnModel().getColumnIndexAtX(e.getX()) == 0) {
                    if (allCheck.isSelected()) {
                        allCheck.setSelected(false);
                        dataTable.getTableHeader().repaint();
                        for (int i = 0; i < dataTable.getRowCount(); i++) {
                            dataTable.getModel().setValueAt(false, i, 0);//把这一列都设成和表头一样
                        }
                    } else {
                        allCheck.setSelected(true);
                        dataTable.getTableHeader().repaint();
                        for (int i = 0; i < dataTable.getRowCount(); i++) {
                            dataTable.getModel().setValueAt(true, i, 0);//把这一列都设成和表头一样
                        }
                    }
                }
            }
        });
        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        nextPageBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                data.clear();
                JSONArray dataList = CommandService.getInstance().listBook(++currentPage, PAGE_SIZE, statusList, "view_count desc",exParam);
                if (dataList != null) {
                    if (dataList.size() < PAGE_SIZE) {
                        nextPageBnt.setEnabled(false);
                    }
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject obj = dataList.getJSONObject(i);
                        Vector item = new Vector();
                        item.add(false);
                        item.add("");
                        item.add(obj.getInt("oid"));
                        item.add(obj.getString("name"));
                        item.add(obj.getString("author"));
                        item.add(obj.getString("cate_name"));
                        item.add(obj.getInt("word_num"));
                        item.add(obj.getString("view_count"));
                        String href = obj.getString("href");
                        item.add(href);
                        data.add(item);
                    }
                } else {
                    nextPageBnt.setEnabled(false);
                }
                dataTable.updateUI();
                forwordPageBnt.setEnabled(true);
            }
        });
        forwordPageBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                data.clear();
                JSONArray dataList = CommandService.getInstance().listBook(--currentPage, PAGE_SIZE, statusList, "view_count desc",exParam);
                if (dataList != null) {
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject obj = dataList.getJSONObject(i);
                        Vector item = new Vector();
                        item.add(false);
                        item.add("");
                        item.add(obj.getInt("oid"));
                        item.add(obj.getString("name"));
                        item.add(obj.getString("author"));
                        item.add(obj.getString("cate_name"));
                        item.add(obj.getInt("word_num"));
                        item.add(obj.getString("view_count"));
                        String href = obj.getString("href");
                        item.add(href);
                        data.add(item);
                    }
                }
                dataTable.updateUI();
                nextPageBnt.setEnabled(true);
                if (currentPage == 1) {
                    forwordPageBnt.setEnabled(false);
                }
            }
        });
        dataTable.setCellSelectionEnabled(true);
        dataTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (e.getClickCount() == 2) {
                    if (dataTable.getColumnModel().getColumnIndexAtX(e.getX()) == 8) {
                        String url = (String) dataTable.getValueAt(dataTable.getSelectedRow(), dataTable.getSelectedColumn());
                        try {
                            Desktop.getDesktop().browse(new URI(url));
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        } catch (URISyntaxException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
        receiveBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int rowCount = dataTable.getRowCount();
                List<Map> idList = new ArrayList<Map>();
                for (int i = 0; i < rowCount; i++) {
                    Boolean checked = (Boolean) dataTable.getValueAt(i, 0);
                    if (checked) {
                        Integer oid = (Integer) dataTable.getValueAt(i, 2);
                        String pCode = ((PartitionComboxItem) dataTable.getValueAt(i, 1)).getCode();
                        if (pCode.trim().length() > 0) {
                            Map item = new HashMap();
                            item.put("oid", oid);
                            item.put("code", pCode);
                            idList.add(item);
                        }
                    }
                }
                if (idList.size() == 0) {
                    JOptionPane.showMessageDialog(root, "请先选择要操作的记录?", "警告信息", JOptionPane.WARNING_MESSAGE | JOptionPane.OK_OPTION);
                } else {
                    Object obj = CommandService.getInstance().receiveData(idList);
                    if (obj != null) {
                        List<Integer> suList = (List<Integer>) obj;
                        if (suList.size() > 0) {
                            if (suList.size() == rowCount && rowCount < PAGE_SIZE) {
                                currentPage = currentPage - 1 > 0 ? (currentPage - 1) : 1;
                            }
                            data.clear();
                            JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "view_count desc",exParam);
                            if (dataList != null) {
                                for (int i = 0; i < dataList.size(); i++) {
                                    JSONObject jo = dataList.getJSONObject(i);
                                    Vector item = new Vector();
                                    item.add(false);
                                    item.add("");
                                    item.add(jo.getInt("oid"));
                                    item.add(jo.getString("name"));
                                    item.add(jo.getString("author"));
                                    item.add(jo.getString("cate_name"));
                                    item.add(jo.getInt("word_num"));
                                    item.add(jo.getString("view_count"));
                                    String href = jo.getString("href");
                                    item.add(href);
                                    data.add(item);
                                }
                            }
                            dataTable.updateUI();
                            if (currentPage == 1) {
                                forwordPageBnt.setEnabled(false);
                            }
                        }
                    }
                }
            }
        });
        notReceiveBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int rowCount = dataTable.getRowCount();
                List<Map> idList = new ArrayList<Map>();
                for (int i = 0; i < rowCount; i++) {
                    Boolean checked = (Boolean) dataTable.getValueAt(i, 0);
                    if (checked) {
                        Integer oid = (Integer) dataTable.getValueAt(i, 2);
                        String pCode = ((PartitionComboxItem) dataTable.getValueAt(i, 1)).getCode();
                        if (pCode.trim().length() > 0) {
                            Map item = new HashMap();
                            item.put("oid", oid);
                            item.put("code", pCode);
                            idList.add(item);
                        }
                    }
                }
                if (idList.size() == 0) {
                    JOptionPane.showMessageDialog(root, "请先选择要操作的记录?", "警告信息", JOptionPane.WARNING_MESSAGE | JOptionPane.OK_OPTION);
                } else {
                    Object obj = CommandService.getInstance().rejectData(idList);
                    if (obj != null) {
                        List<Integer> suList = (List<Integer>) obj;
                        if (suList.size() > 0) {
                            if (suList.size() == rowCount && rowCount < PAGE_SIZE) {
                                currentPage--;
                            }
                            data.clear();
                            JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "view_count desc", exParam);
                            if (dataList != null) {
                                for (int i = 0; i < dataList.size(); i++) {
                                    JSONObject jo = dataList.getJSONObject(i);
                                    Vector item = new Vector();
                                    item.add(false);
                                    item.add("");
                                    item.add(jo.getInt("oid"));
                                    item.add(jo.getString("name"));
                                    item.add(jo.getString("author"));
                                    item.add(jo.getString("cate_name"));
                                    item.add(jo.getInt("word_num"));
                                    item.add(jo.getString("view_count"));
                                    String href = jo.getString("href");
                                    item.add(href);
                                    data.add(item);
                                }
                            }
                            dataTable.updateUI();
                            if (currentPage == 1) {
                                forwordPageBnt.setEnabled(false);
                            }
                        }
                    }
                }
            }
        });
        applyBnt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SourceTypeItem sItem = (SourceTypeItem) sourceTypeCombo.getSelectedItem();
                exParam.clear();
                exParam.put("sourceType", sItem.getType());
                exParam.put("title", titleInput.getText().trim());
                data.clear();
                JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "view_count desc", exParam);
                if (dataList != null) {
                    if (dataList.size() < PAGE_SIZE) {
                        nextPageBnt.setEnabled(false);
                    }
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject jo = dataList.getJSONObject(i);
                        Vector item = new Vector();
                        item.add(false);
                        item.add("");
                        item.add(jo.getInt("oid"));
                        item.add(jo.getString("name"));
                        item.add(jo.getString("author"));
                        item.add(jo.getString("cate_name"));
                        item.add(jo.getInt("word_num"));
                        item.add(jo.getString("view_count"));
                        String href = jo.getString("href");
                        item.add(href);
                        data.add(item);
                    }
                }
                dataTable.updateUI();
                currentPage = 1;
                if (currentPage == 1) {
                    forwordPageBnt.setEnabled(false);
                }
            }
        });
    }

    public JPanel getRoot() {
        return root;
    }
}
